<template>
    <div>
        <div class="header">
            <el-form ref="form" label-width="80px" :inline="true">
                <el-form-item>
                    <el-input v-model="roleName" placeholder="角色名称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button @click="clear">清空</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div>
            <el-button type="primary" @click="addRole">添加</el-button>
            <el-button type="danger" :disabled="selectedRoles.length === 0" @click="removeRoles">批量删除</el-button>
        </div>
        <el-table ref="multipleTable" :data="roleLsit" style="width: 100%;margin-top: 15px;"
            @selection-change="handleSelectionChange" :loading="roleLoading" border>
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column label="序号" width="80" type="index" align="center">
            </el-table-column>
            <el-table-column prop="roleName" label="角色名称">
                <template slot-scope="{$index, row}">
                    <template v-if="row.edit">
                        <el-input v-model="row.roleName" size="small" style="padding-right: 100px;"></el-input>
                        <el-button type="warning" size="mini" icon="el-icon-refresh"
                            style="position: absolute;right:15px;top: 10px;" @click="cancelRole(row)">取消</el-button>
                    </template>
                    <span v-else>{{ row.roleName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="{$index, row}">
                    <div style="display: flex;justify-content: center;">
                        <el-button type="info" icon="el-icon-info" size="mini" @click="toRoleAuth(row)"></el-button>
                        <el-button v-if="row.edit" type="primary" icon="el-icon-check" size="mini"
                            @click="confirmEditRole(row)"></el-button>
                        <el-button v-else type="primary" icon="el-icon-edit" size="mini"
                            @click="editRole(row)"></el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRole(row)"></el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
            :page-sizes="[3, 5, 10]" :page-size="limit" layout="prev, pager, next, jumper, ->, sizes, total"
            :total="total">
        </el-pagination>

    </div>
</template>

<script>
export default {
    name: 'Role',
    data() {
        return {
            roleName: '',
            roleLsit: [],
            page: 1,
            limit: 3,
            total: 0,
            roleLoading: false,
            selectedRoles: [],
            RoleFormVisible: false,//添加角色弹出框
        }
    },
    mounted() {
        this.getRolesList()
    },
    methods: {
        // 获取角色列表
        async getRolesList() {
            this.roleLoading = true
            const { page, limit, roleName } = this
            let result = await this.$API.role.reqGetRoleList(page, limit, roleName)
            if (result.code == 20000) {
                const { total, items } = result.data
                this.total = total
                this.roleLsit = items.map(item => {
                    // 是否显示编辑框
                    item.edit = false
                    // 用于取消按钮能回到原始的角色名称
                    item.originRoleName = item.roleName
                    return item
                });
                this.roleLoading = false
            }
        },
        // 选择当前页
        handleCurrentChange(page) {
            this.page = page
            this.getRolesList()
        },
        // 更改每页个数
        handleSizeChange(limit) {
            this.page = 1
            this.limit = limit
            this.getRolesList()
        },
        // 列表复选框选择
        handleSelectionChange(selected) {
            this.selectedRoles = selected
        },
        // 搜索有关键字的列表
        search() {
            this.page = 1
            this.getRolesList()
        },
        // 清空关键字
        clear() {
            this.roleName = ''
            this.search()
        },
        // 添加角色
        addRole() {
            this.$prompt('请输入新名称', '添加角色', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(async ({ value }) => {
                if (value.trim().length > 0) {
                    let result = await this.$API.role.reqSaveRole({ roleName: value.trim() })
                    if (result.code == 20000) {
                        this.$message({ type: 'success', message: '添加角色成功' })
                    } else {
                        this.$message({ type: 'danger', message: '添加角色失败' })
                    }
                    this.getRolesList()
                } else {
                    this.$message({ type: 'warning', message: '不允许角色名称为空' })
                }
            }).catch(() => {
                this.$message({ type: 'warning', message: '取消添加' })
            })
        },
        // 保存角色
        // 编辑角色名称
        editRole(role) {
            role.edit = true
        },
        // 取消更改名称
        cancelRole(role) {
            role.edit = false
            role.roleName = role.originRoleName
            this.$message({ type: 'warning', message: '取消角色修改' })
        },
        // 确认更改名称
        async confirmEditRole(role) {
            let result = await this.$API.role.reqUpdateRole({ id: role.id, roleName: role.roleName })
            if (result.code == 20000) {
                this.$message({ type: 'success', message: '角色修改成功' })
                this.getRolesList()
            }
        },
        // 删除角色
        deleteRole(role) {
            this.$confirm(`确定删除${role.roleName}?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let result = await this.$API.role.reqDeleteRole(role.id)
                if (result.code == 20000) {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    })
                    if (this.roleLsit <= 1 && this.page > 1) {
                        this.page -= 1
                    }
                    this.getRolesList()
                } else {
                    this.$message({
                        type: 'danger',
                        message: '删除失败!'
                    });
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 批量删除
        removeRoles() {
            this.$confirm("确定删除?", '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let list = []
                let arr = []
                this.selectedRoles.forEach(async (item) => {
                    let res = await this.$API.role.reqDeleteRole(item.id)
                    if (res.code == 20000) {
                        list.push("ok")
                        arr.push("ok")
                        this.$message({ type: 'success', message: `删除${item.roleName}成功` })
                        if (list.length == this.selectedRoles.length) {
                            this.$message({ type: 'success', message: `全部删除成功` })
                            this.getRolesList()
                        }
                        if (arr.length == this.selectedRoles.length) {
                            this.getRolesList()
                        }
                    } else {
                        arr.push("error")
                        this.$message({ type: 'info', message: `删除${item.roleName}失败` })
                        if (arr.length == this.selectedRoles.length) {
                            this.getRolesList()
                        }
                    }
                });

            }).catch((error) => {
                this.$message({ type: 'info', message: '取消删除' })
            })
        },
        // 进入角色分配权限页
        toRoleAuth(row) {
            this.$router.push(`/acl/role/auth/${row.id}?roleName=${row.roleName}`)
        }
    }
}
</script>

<style></style>